<template>
  <div class="schedule-container">
    <div class="header">
      <h2>排班管理</h2>
      <div class="button-group">
        <el-button type="primary" @click="showAssignDialog" class="add-button">手动排班</el-button>
        <el-button type="success" @click="showAutoAssignDialog" class="add-button">自动排班</el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete" 
          :disabled="selectedSchedules.length === 0"
          class="delete-button"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 添加过滤条件区域 -->
    <div class="filter-container">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="min-width: 300px;"
          />
        </el-form-item>
        <el-form-item label="员工">
          <el-select 
            v-model="filterEmployee" 
            placeholder="按员工筛选" 
            clearable 
            filterable 
            remote
            :remote-method="handleEmployeeSearch"
            :loading="employeeSearchLoading"
            style="min-width: 180px;"
          >
            <el-option
              v-for="employee in filteredEmployees"
              :key="employee.ID"
              :label="employee.name"
              :value="employee.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班次">
          <el-select 
            v-model="filterShift" 
            placeholder="按班次筛选" 
            clearable 
            filterable 
            remote
            :remote-method="handleShiftSearch"
            :loading="shiftSearchLoading"
            style="min-width: 180px;"
          >
            <el-option
              v-for="shift in filteredShifts"
              :key="shift.ID"
              :label="shift.name"
              :value="shift.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select 
            v-model="filterProduct" 
            placeholder="按产品筛选" 
            clearable 
            filterable 
            remote
            :remote-method="handleProductSearch"
            :loading="productSearchLoading"
            style="min-width: 180px;"
          >
            <el-option
              v-for="product in filteredProducts"
              :key="product.value"
              :label="product.label"
              :value="product.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterExpired" placeholder="按状态筛选" clearable style="min-width: 180px;">
            <el-option label="显示全部" value="" />
            <el-option label="隐藏已过期" value="hideExpired" />
            <el-option label="仅显示已过期" value="onlyExpired" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilters" class="filter-button">应用筛选</el-button>
          <el-button @click="resetFilters" class="filter-button">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 排班列表 -->
    <el-table
      v-loading="loading"
      :data="paginatedSchedules"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      class="schedule-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="员工" min-width="120">
        <template #default="{ row }">
          <el-tooltip :content="`ID: ${row.employee_id}`" placement="top">
            <span class="employee-name">{{ getEmployeeName(row.employee_id) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="班次" min-width="120">
        <template #default="{ row }">
          <el-tooltip :content="`ID: ${row.shift_id}`" placement="top">
            <span class="shift-name">{{ renderShiftInfo(row) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="产品" min-width="120">
        <template #default="{ row }">
          <el-tag size="small" type="info" effect="plain" v-if="!getShiftProductName(row.shift_id) || getShiftProductName(row.shift_id) === '无产品'">
            无产品
          </el-tag>
          <el-tag size="small" type="success" effect="plain" v-else>
            {{ getShiftProductName(row.shift_id) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="日期" min-width="120">
        <template #default="{ row }">
          <el-tooltip :content="formatDateTime(row.date)" placement="top">
            <span class="date">{{ formatDate(row.date) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="isExpired(row.date) ? 'danger' : 'success'" effect="light">
            {{ isExpired(row.date) ? '已过期' : '已排班' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="showEditDialog(row)">调整</el-button>
          <el-popconfirm
            title="确定要删除这条排班记录吗？"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button size="small" type="danger" plain>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredSchedules.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 手动排班对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="scheduleForm" label-width="100px">
        <el-form-item label="员工列表">
          <div class="employee-list-container">
            <div class="employee-list-controls">
              <el-select 
                v-model="selectedEmployee" 
                placeholder="选择员工"
                filterable
                style="width: 70%"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.ID"
                  :label="employee.name"
                  :value="employee"
                />
              </el-select>
              <el-button type="primary" @click="addEmployeeToList" :disabled="!selectedEmployee">添加</el-button>
            </div>
            
            <div class="employee-list">
              <el-tag
                v-for="(employee, index) in scheduleForm.employeeList"
                :key="index"
                closable
                @close="removeEmployeeFromList(index)"
                class="employee-tag"
              >
                {{ employee.name }}
              </el-tag>
              <div v-if="scheduleForm.employeeList.length === 0" class="empty-list-hint">
                请添加员工到排班列表
              </div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="班次">
          <el-select 
            v-model="scheduleForm.shift_id" 
            placeholder="选择班次" 
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="shift in shifts"
              :key="shift.ID"
              :label="`${shift.name}${shift.product_name ? ' - ' + shift.product_name : ''}`"
              :value="shift.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="scheduleForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="scheduleForm.status" placeholder="选择状态" style="width: 100%">
            <el-option label="已排班" value="已排班" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动排班对话框 -->
    <el-dialog
      title="自动排班"
      v-model="autoDialogVisible"
      width="600px"
    >
      <el-form :model="autoScheduleForm" label-width="120px">
        <el-form-item label="排班模式">
          <el-radio-group v-model="autoScheduleForm.mode">
            <el-radio label="rotation">轮换模式(ABCABC)</el-radio>
            <el-radio label="consecutive">连续模式(AABBCC)</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="员工选择" prop="employeeIds">
          <el-select 
            v-model="autoScheduleForm.employeeIds" 
            multiple 
            filterable
            placeholder="选择员工" 
            style="width: 100%"
          >
            <el-option
              v-for="employee in employees"
              :key="employee.ID"
              :label="employee.name"
              :value="employee.ID"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="班次选择" prop="shift_id">
          <el-select 
            v-model="autoScheduleForm.shift_id" 
            placeholder="选择班次" 
            filterable
            style="width: 100%"
            @change="handleShiftChange"
          >
            <el-option
              v-for="shift in shifts"
              :key="shift.ID"
              :label="`${shift.name}${shift.product_name ? ' - ' + shift.product_name : ''}`"
              :value="shift.ID"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="autoScheduleForm.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="autoScheduleForm.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item v-if="autoScheduleForm.mode === 'consecutive'" label="连续天数" prop="consecutiveDays">
          <el-input-number v-model="autoScheduleForm.consecutiveDays" :min="1" :max="7" />
        </el-form-item>
        
        <el-form-item label="排班状态" prop="status">
          <el-select v-model="autoScheduleForm.status" placeholder="选择状态" style="width: 100%">
            <el-option label="已排班" value="已排班" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="班次信息" v-if="autoScheduleForm.shift_id">
          <div class="shift-info">
            <p><strong>开始时间:</strong> {{ formatDateTime(autoScheduleForm.startTime) }}</p>
            <p><strong>结束时间:</strong> {{ formatDateTime(autoScheduleForm.endTime) }}</p>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="autoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAutoSchedule">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.schedule-container {
  padding: 20px;
  background-color: #f5f5f7;
  min-height: calc(100vh - 60px);
  border-radius: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #1d1d1f;
}

.button-group {
  display: flex;
  gap: 10px;
}

.add-button, .delete-button, .filter-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-container {
  background-color: white;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.schedule-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.schedule-table :deep(.el-table__header) {
  background-color: #f5f5f7;
}

.schedule-table :deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

.schedule-table :deep(.el-table__row:hover) {
  background-color: #f0f0f2;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.employee-name, .shift-name, .date {
  font-weight: 500;
  color: #1d1d1f;
}

.employee-list-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.employee-list-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.employee-list {
  min-height: 80px;
  padding: 10px;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-content: flex-start;
  background-color: #fff;
}

.employee-tag {
  margin-right: 5px;
  margin-bottom: 5px;
  border-radius: 6px;
}

.empty-list-hint {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  width: 100%;
  text-align: center;
  padding: 20px 0;
}

:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #f0f0f2;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f2;
}

:deep(.el-button) {
  border-radius: 8px;
}

:deep(.el-tag) {
  border-radius: 6px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100%;
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .button-group {
    flex-direction: column;
  }
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-select-dropdown__empty) {
  padding: 10px;
  color: #909399;
}

:deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

:deep(.el-select .el-input__suffix) {
  color: #909399;
}

:deep(.el-select .el-input__inner:focus) {
  border-color: var(--el-color-primary);
}

:deep(.el-select-dropdown) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-select-dropdown__item.selected) {
  color: var(--el-color-primary);
  font-weight: bold;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}
</style>


<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useScheduleStore } from '../stores/schedule.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useScheduleStore()
const loading = ref(false)
const dialogVisible = ref(false)
const autoDialogVisible = ref(false)
const dialogTitle = ref('')
const schedules = ref([])

// 添加过滤相关的状态
const filterProduct = ref('')
const filterExpired = ref('')
const filterEmployee = ref('')
const filterShift = ref('')
const dateRange = ref([])
const productOptions = ref([])

const employees = computed(() => store.employees)
const shifts = computed(() => store.shifts)

// 根据过滤条件筛选排班记录
const filteredSchedules = computed(() => {
  let result = [...schedules.value]
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    startDate.setHours(0, 0, 0, 0)
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(schedule => {
      const scheduleDate = new Date(schedule.date)
      return scheduleDate >= startDate && scheduleDate <= endDate
    })
  }
  
  // 按员工筛选
  if (filterEmployee.value) {
    result = result.filter(schedule => schedule.employee_id === filterEmployee.value)
  }
  
  // 按班次筛选
  if (filterShift.value) {
    result = result.filter(schedule => schedule.shift_id === filterShift.value)
  }
  
  // 按产品筛选
  if (filterProduct.value) {
    result = result.filter(schedule => {
      const shift = shifts.value.find(s => s.ID === schedule.shift_id)
      return shift && shift.product_id === parseInt(filterProduct.value)
    })
  }
  
  // 按过期状态筛选
  if (filterExpired.value === 'hideExpired') {
    result = result.filter(schedule => !isExpired(schedule.date))
  } else if (filterExpired.value === 'onlyExpired') {
    result = result.filter(schedule => isExpired(schedule.date))
  }
  
  return result
})

const scheduleForm = ref({
  employeeList: [],
  shift_id: '',
  dateRange: [],
  status: '已排班'
})

const autoScheduleForm = ref({
  mode: 'rotation', // 'rotation' 或 'consecutive'
  employeeIds: [],
  shift_id: '',
  startDate: '',
  endDate: '',
  startTime: '', // 添加开始时间
  endTime: '',   // 添加结束时间
  consecutiveDays: 2,
  status: '已排班'
})

const selectedEmployee = ref(null)

const addEmployeeToList = () => {
  if (selectedEmployee.value) {
    scheduleForm.value.employeeList.push(selectedEmployee.value)
    selectedEmployee.value = null
  }
}

const removeEmployeeFromList = (index) => {
  scheduleForm.value.employeeList.splice(index, 1)
}

const resetForm = () => {
  scheduleForm.value = {
    employeeList: [],
    shift_id: '',
    dateRange: [],
    status: '已排班'
  }
  selectedEmployee.value = null
}

const resetAutoForm = () => {
  autoScheduleForm.value = {
    mode: 'rotation',
    employeeIds: [],
    shift_id: '',
    startDate: '',
    endDate: '',
    startTime: '',
    endTime: '',
    consecutiveDays: 2,
    status: '已排班'
  }
}

// 判断日期是否已过期（早于今天）
const isExpired = (dateStr) => {
  if (!dateStr) return false
  const scheduleDate = new Date(dateStr)
  scheduleDate.setHours(0, 0, 0, 0)
  
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  return scheduleDate < today
}

// 应用过滤条件
const applyFilters = () => {
  // 已经通过计算属性自动应用了过滤条件
  ElMessage.success('筛选条件已应用')
}

// 重置过滤条件
const resetFilters = () => {
  filterProduct.value = ''
  filterExpired.value = ''
  filterEmployee.value = ''
  filterShift.value = ''
  dateRange.value = []
  ElMessage.success('筛选条件已重置')
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未设置'
  const date = new Date(dateTime)
  return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
}

const getEmployeeName = (employeeId) => {
  const employee = employees.value.find(e => e.ID === employeeId)
  return employee ? employee.name : ''
}

const getShiftName = (shiftId) => {
  const shift = shifts.value.find(s => s.ID === shiftId)
  return shift ? shift.name : ''
}

// 获取班次的产品名称
const getShiftProductName = (shiftId) => {
  const shift = shifts.value.find(s => s.ID === shiftId)
  return shift ? shift.product_name || '无产品' : '无产品'
}

// 格式化班次时间
const formatShiftTime = (shift) => {
  if (!shift) return ''
  
  if (shift.is_full_day) return '全天'
  
  const startTime = new Date(shift.start_time)
  const endTime = new Date(shift.end_time)
  
  return `${startTime.getHours()}:${startTime.getMinutes().toString().padStart(2, '0')} - ${endTime.getHours()}:${endTime.getMinutes().toString().padStart(2, '0')}`
}

// 更新自动排班表单中的班次选择处理函数
const handleShiftChange = () => {
  if (!autoScheduleForm.value.shift_id) {
    autoScheduleForm.value.startTime = ''
    autoScheduleForm.value.endTime = ''
    return
  }
  
  const selectedShift = shifts.value.find(s => s.ID === autoScheduleForm.value.shift_id)
  if (selectedShift) {
    // 如果是全天班次，设置默认的开始和结束时间
    if (selectedShift.is_full_day) {
      // 设置为当前日期的00:00到23:59
      const today = new Date()
      
      const startDate = new Date(today)
      startDate.setHours(0, 0, 0, 0)
      autoScheduleForm.value.startTime = startDate
      
      const endDate = new Date(today)
      endDate.setHours(23, 59, 0, 0)
      autoScheduleForm.value.endTime = endDate
    } else {
      // 如果是固定时间班次，使用班次的开始和结束时间
      autoScheduleForm.value.startTime = selectedShift.start_time
      autoScheduleForm.value.endTime = selectedShift.end_time
    }
  }
}

const showAssignDialog = () => {
  dialogTitle.value = '分配班次'
  resetForm()
  dialogVisible.value = true
}

const showAutoAssignDialog = () => {
  resetAutoForm()
  autoDialogVisible.value = true
}

const showEditDialog = (row) => {
  dialogTitle.value = '调整排班'
  
  // 查找员工信息
  const employee = employees.value.find(e => e.ID === row.employee_id)
  
  scheduleForm.value = { 
    ID: row.ID,
    employeeList: employee ? [employee] : [],
    shift_id: row.shift_id,
    dateRange: [row.date, row.date],
    status: row.status
  }
  selectedEmployee.value = null
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (dialogTitle.value === '分配班次') {
      // 验证表单
      if (!scheduleForm.value.employeeList || scheduleForm.value.employeeList.length === 0) {
        ElMessage.error('请添加至少一名员工到排班列表')
        return
      }
      
      if (!scheduleForm.value.shift_id) {
        ElMessage.error('请选择班次')
        return
      }
      
      if (!scheduleForm.value.dateRange || scheduleForm.value.dateRange.length !== 2) {
        ElMessage.error('请选择日期范围')
        return
      }
      
      const startDate = new Date(scheduleForm.value.dateRange[0])
      const endDate = new Date(scheduleForm.value.dateRange[1])
      
      // 验证结束日期不能早于开始日期
      if (endDate < startDate) {
        ElMessage.error('结束日期不能早于开始日期')
        return
      }
      
      // 生成日期范围
      const dateRange = []
      const currentDate = new Date(startDate)
      while (currentDate <= endDate) {
        dateRange.push(new Date(currentDate))
        currentDate.setDate(currentDate.getDate() + 1)
      }
      
      // 创建排班记录 - 每天按顺序排一个人
      const newSchedules = []
      const employeeList = scheduleForm.value.employeeList
      
      if (employeeList.length > 0) {
        dateRange.forEach((date, dateIndex) => {
          // 按照员工列表顺序循环排班
          const employeeIndex = dateIndex % employeeList.length
          const employee = employeeList[employeeIndex]
          
          newSchedules.push({
            employee_id: employee.ID,
            shift_id: scheduleForm.value.shift_id,
            date: date.toISOString(),
            status: scheduleForm.value.status
          })
        })
      }
      
      // 批量创建排班
      loading.value = true
      let successCount = 0
      let failedCount = 0
      let errorMessages = new Set()
      
      try {
        for (const schedule of newSchedules) {
          try {
            await store.createSchedule(schedule)
            successCount++
          } catch (error) {
            failedCount++
            // 提取错误信息
            const errorMessage = error.response?.data?.error || error.message
            errorMessages.add(errorMessage)
          }
        }
        
        // 根据结果显示不同的消息
        if (successCount > 0 && failedCount === 0) {
          ElMessage.success(`成功创建 ${successCount} 条排班记录`)
          dialogVisible.value = false
        } else if (successCount > 0 && failedCount > 0) {
          ElMessage({
            message: `成功创建 ${successCount} 条排班记录，失败 ${failedCount} 条`,
            type: 'warning',
            duration: 5000
          })
          // 显示错误详情
          if (errorMessages.size > 0) {
            setTimeout(() => {
              ElMessage({
                message: `失败原因: ${Array.from(errorMessages).join('; ')}`,
                type: 'warning',
                duration: 8000
              })
            }, 300)
          }
        } else {
          ElMessage.error(`所有排班创建失败，共 ${failedCount} 条`)
          // 显示错误详情
          if (errorMessages.size > 0) {
            setTimeout(() => {
              ElMessage({
                message: `失败原因: ${Array.from(errorMessages).join('; ')}`,
                type: 'error',
                duration: 8000
              })
            }, 300)
          }
        }
        
        if (successCount > 0) {
          await fetchSchedules()
          if (successCount > 0 && failedCount === 0) {
            dialogVisible.value = false
          }
        }
      } catch (error) {
        console.error('创建排班失败:', error)
        ElMessage.error('排班失败: ' + (error.response?.data?.error || error.message))
      } finally {
        loading.value = false
      }
    } else {
      // 编辑模式
      if (!scheduleForm.value.ID) {
        ElMessage.error('无效的排班ID')
        return
      }
      
      if (scheduleForm.value.employeeList.length === 0) {
        ElMessage.error('请添加至少一名员工到排班列表')
        return
      }
      
      // 编辑模式下只更新单条记录
      const updateData = {
        ID: scheduleForm.value.ID,
        employee_id: scheduleForm.value.employeeList[0].ID,
        shift_id: scheduleForm.value.shift_id,
        date: new Date(scheduleForm.value.dateRange[0]).toISOString(),
        status: scheduleForm.value.status
      }
      
      await store.updateSchedule(updateData)
      ElMessage.success('调整成功')
      dialogVisible.value = false
      await fetchSchedules()
    }
  } catch (error) {
    console.error('排班操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 自动排班处理函数
const handleAutoSchedule = async () => {
  try {
    // 验证表单
    if (!autoScheduleForm.value.employeeIds || autoScheduleForm.value.employeeIds.length === 0) {
      ElMessage.error('请选择至少一名员工')
      return
    }
    
    if (!autoScheduleForm.value.shift_id) {
      ElMessage.error('请选择班次')
      return
    }
    
    if (!autoScheduleForm.value.startDate || !autoScheduleForm.value.endDate) {
      ElMessage.error('请选择开始和结束日期')
      return
    }
    
    const startDate = new Date(autoScheduleForm.value.startDate)
    const endDate = new Date(autoScheduleForm.value.endDate)
    
    // 验证结束日期不能早于开始日期
    if (endDate < startDate) {
      ElMessage.error('结束日期不能早于开始日期')
      return
    }
    
    // 获取选中的班次信息
    const selectedShift = shifts.value.find(s => s.ID === autoScheduleForm.value.shift_id)
    if (!selectedShift) {
      ElMessage.error('无法获取所选班次信息')
      return
    }
    
    // 验证班次的开始时间和结束时间
    if (!selectedShift.start_time || !selectedShift.end_time) {
      ElMessage.error('所选班次缺少开始时间或结束时间信息')
      return
    }
    
    // 生成日期范围
    const dateRange = []
    const currentDate = new Date(startDate)
    while (currentDate <= endDate) {
      dateRange.push(new Date(currentDate))
      currentDate.setDate(currentDate.getDate() + 1)
    }
    
    // 根据不同模式生成排班
    const newSchedules = []
    const employeeIds = autoScheduleForm.value.employeeIds
    const shift_id = autoScheduleForm.value.shift_id
    const status = autoScheduleForm.value.status
    
    if (autoScheduleForm.value.mode === 'rotation') {
      // 轮换模式 (ABCABC)
      dateRange.forEach((date, index) => {
        const employeeIndex = index % employeeIds.length
        
        // 创建排班记录
        const scheduleDate = new Date(date)
        
        newSchedules.push({
          employee_id: employeeIds[employeeIndex],
          shift_id: shift_id,
          date: scheduleDate.toISOString(),
          status: status
        })
      })
    } else {
      // 连续模式 (AABBCC)
      const consecutiveDays = autoScheduleForm.value.consecutiveDays
      let currentEmployeeIndex = 0
      let daysAssigned = 0
      
      dateRange.forEach(date => {
        // 创建排班记录
        const scheduleDate = new Date(date)
        
        newSchedules.push({
          employee_id: employeeIds[currentEmployeeIndex],
          shift_id: shift_id,
          date: scheduleDate.toISOString(),
          status: status
        })
        
        daysAssigned++
        
        // 检查是否需要切换到下一个员工
        if (daysAssigned >= consecutiveDays) {
          currentEmployeeIndex = (currentEmployeeIndex + 1) % employeeIds.length
          daysAssigned = 0
        }
      })
    }
    
    // 批量创建排班
    loading.value = true
    let successCount = 0
    let failedCount = 0
    let errorMessages = new Set()
    
    try {
      for (const schedule of newSchedules) {
        try {
          await store.createSchedule(schedule)
          successCount++
        } catch (error) {
          failedCount++
          // 提取错误信息
          const errorMessage = error.response?.data?.error || error.message
          errorMessages.add(errorMessage)
        }
      }
      
      // 根据结果显示不同的消息
      if (successCount > 0 && failedCount === 0) {
        ElMessage.success(`成功创建 ${successCount} 条排班记录`)
        autoDialogVisible.value = false
      } else if (successCount > 0 && failedCount > 0) {
        ElMessage({
          message: `成功创建 ${successCount} 条排班记录，失败 ${failedCount} 条`,
          type: 'warning',
          duration: 5000
        })
        // 显示错误详情
        if (errorMessages.size > 0) {
          setTimeout(() => {
            ElMessage({
              message: `失败原因: ${Array.from(errorMessages).join('; ')}`,
              type: 'warning',
              duration: 8000
            })
          }, 300)
        }
      } else {
        ElMessage.error(`所有排班创建失败，共 ${failedCount} 条`)
        // 显示错误详情
        if (errorMessages.size > 0) {
          setTimeout(() => {
            ElMessage({
              message: `失败原因: ${Array.from(errorMessages).join('; ')}`,
              type: 'error',
              duration: 8000
            })
          }, 300)
        }
      }
      
      if (successCount > 0) {
        await fetchSchedules()
        if (successCount > 0 && failedCount === 0) {
          autoDialogVisible.value = false
        }
      }
    } catch (error) {
      console.error('创建排班失败:', error)
      ElMessage.error('自动排班失败: ' + (error.response?.data?.error || error.message))
    } finally {
      loading.value = false
    }
  } catch (error) {
    console.error('自动排班出错:', error)
    ElMessage.error('自动排班失败: ' + (error.response?.data?.error || error.message))
  }
}

const handleDelete = async (row) => {
  try {
    if (!row || !row.ID) {
      ElMessage.error('无效的排班ID')
      return
    }
    await store.deleteSchedule(row.ID)
    ElMessage.success('删除成功')
    await fetchSchedules()
  } catch (error) {
    console.error('删除排班出错:', error)
    ElMessage.error('删除失败')
  }
}

const fetchSchedules = async () => {
  loading.value = true
  try {
    await store.fetchSchedules()
    schedules.value = store.schedules
  } catch (error) {
    ElMessage.error('获取排班列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化产品选项
const initProductOptions = () => {
  const products = new Map()
  
  shifts.value.forEach(shift => {
    if (shift.product_id && !products.has(shift.product_id)) {
      products.set(shift.product_id, shift.product_name || `产品 ${shift.product_id}`)
    }
  })
  
  productOptions.value = Array.from(products).map(([value, label]) => ({ value, label }))
}

// 监听班次选择变化
watch(() => autoScheduleForm.value.shift_id, (newVal) => {
  if (newVal) {
    handleShiftChange()
  }
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

// 获取分页后的数据
const paginatedSchedules = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredSchedules.value.slice(start, end)
})

// 在表格中显示班次信息
const renderShiftInfo = (row) => {
  const shift = shifts.value.find(s => s.ID === row.shift_id)
  if (!shift) return '未知班次'
  
  return `${shift.name} (${formatShiftTime(shift)})`
}

// 多选相关
const selectedSchedules = ref([])

const handleSelectionChange = (selection) => {
  selectedSchedules.value = selection
}

const handleBatchDelete = async () => {
  if (selectedSchedules.value.length === 0) {
    ElMessage.warning('请至少选择一条排班记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedSchedules.value.length} 条排班记录吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedSchedules.value.map(item => item.ID)
    loading.value = true
    
    try {
      const deletedCount = await store.batchDeleteSchedules(ids)
      ElMessage.success(`成功删除 ${deletedCount} 条排班记录`)
      await fetchSchedules()
    } catch (error) {
      console.error('批量删除排班出错:', error)
      ElMessage.error('批量删除失败: ' + (error.response?.data?.error || error.message))
    } finally {
      loading.value = false
    }
  } catch {
    // 用户取消删除操作
  }
}

// 搜索相关
const employeeSearchQuery = ref('')
const shiftSearchQuery = ref('')
const productSearchQuery = ref('')
const employeeSearchLoading = ref(false)
const shiftSearchLoading = ref(false)
const productSearchLoading = ref(false)

// 根据查询过滤员工
const filteredEmployees = computed(() => {
  const query = employeeSearchQuery.value.toLowerCase().trim()
  if (!query) return employees.value
  
  return employees.value.filter(employee => 
    employee.name.toLowerCase().includes(query)
  )
})

// 根据查询过滤班次
const filteredShifts = computed(() => {
  const query = shiftSearchQuery.value.toLowerCase().trim()
  if (!query) return shifts.value
  
  return shifts.value.filter(shift => 
    shift.name.toLowerCase().includes(query) || 
    (shift.product_name && shift.product_name.toLowerCase().includes(query))
  )
})

// 根据查询过滤产品
const filteredProducts = computed(() => {
  const query = productSearchQuery.value.toLowerCase().trim()
  if (!query) return productOptions.value
  
  return productOptions.value.filter(product => 
    product.label.toLowerCase().includes(query)
  )
})

// 处理搜索输入
const handleEmployeeSearch = (query) => {
  employeeSearchLoading.value = true
  employeeSearchQuery.value = query
  setTimeout(() => {
    employeeSearchLoading.value = false
  }, 200)
}

const handleShiftSearch = (query) => {
  shiftSearchLoading.value = true
  shiftSearchQuery.value = query
  setTimeout(() => {
    shiftSearchLoading.value = false
  }, 200)
}

const handleProductSearch = (query) => {
  productSearchLoading.value = true
  productSearchQuery.value = query
  setTimeout(() => {
    productSearchLoading.value = false
  }, 200)
}

onMounted(async () => {
  await Promise.all([
    store.fetchEmployees(),
    store.fetchShifts(),
    fetchSchedules()
  ])
  
  // 初始化产品选项
  initProductOptions()
})
</script>